###############EchoServer Groups
###########meet bug: It will be send message to all of clients when start more Server instance.
import threading, socketserver, logging

FORMAT = "%(asctime)s %(threadName)s %(thread)d %(message)s "
logging.basicConfig(format=FORMAT, level=logging.INFO)
#EchoServer
class EchoHandler(socketserver.BaseRequestHandler):
    # def __init__(self, request, client_address, server):
    # super().__init__(request, client_address, server)

    clients = {}
    print(clients)

    def setup(self):
        super().setup()
        self.event = threading.Event()
        self.lock = threading.Lock()
        with self.lock:
            self.clients[self.client_address] = self.request
            print('1', len(self.clients), self.clients)
        print('0', self.clients)

    def finish(self):
        super().finish()
        self.event.set()
        # with self.lock:
        # print(self.clients.pop(self.client_address))

    def handle(self):
        super().handle()
        print('handle', self.clients)
        while not self.event.is_set():
            data = self.request.recv(1024)

            if not data or data == b'quit':
                print(data)
                with self.lock:
                    print('1-1', self.clients.pop(self.client_address))
                break
            print('2', len(self.clients), self.clients)
            msg = "{} ~~~~".format(data.decode()).encode()

            with self.lock:
                for c in self.clients.values():
                    print('3',c)
                    c.send(msg)
            print('-' * 30)
            logging.info(threading.enumerate())

server1 = socketserver.ThreadingTCPServer(('127.0.0.1', 60000), EchoHandler)

# server1.clients = {}
threading.Thread(target=server1.serve_forever,name='server1').start()
# server2 = socketserver.ThreadingTCPServer(('127.0.0.1', 60001), EchoHandler)
# threading.Thread(target=server2.serve_forever,name='server2').start()
while True:
    cmd = input('>>>')
    if cmd == 'quit':
        server1.server_close()
        server2.server_close()
        break
    print(threading.enumerate())
print('=' * 30)

# 做的不错, 不过文件名不要取成和python模块名一样, 这样的话, 会造成导入bug, 至于多个server的情况, 可以每个server写一个clients属性
